package com.example.sunming.fanshe;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: sunming
 * @date: 2020/4/10
 * @description:
 */
public class TestClassMethodForAttr {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException,
            InvocationTargetException, InstantiationException, NoSuchMethodException {
        Class<Person> clazz2 = Person.class;
        Constructor<Person> constructor = clazz2.getConstructor(String.class, Integer.class);
        Person obj = constructor.newInstance("sunming", 22);
        // 4、获得类完整名字
        String name = clazz2.getName();
        System.out.println("完整名字:" + name);
        // 5、获得不包含包路径
        String simpleName = clazz2.getSimpleName();
        System.out.println(simpleName);
        // 6、获得类中公共类型属性
        Field[] fields = clazz2.getFields();
        StringBuilder sb = new StringBuilder();
        for (Field field : fields) {
            sb.append(field.getName()).append("--");
        }
        System.out.println("类中公共属性:" + sb.toString());
        // 7、类中全部类型包括私有属性
        Field[] declaredFields = clazz2.getDeclaredFields();
        sb = new StringBuilder();
        for (Field declaredField : declaredFields) {
            sb.append(declaredField.getName()).append("--");
        }
        System.out.println("类中所有包括私有属性:" + sb.toString());
        // 8、获得公共指定属性值
        Field age = clazz2.getField("age");
        Object o1 = age.get(obj);
        System.out.println("公共指定属性:" + o1);
        // 8、获得私有指定属性值
        Field name1 = clazz2.getDeclaredField("name");
        name1.setAccessible(true); //设置为true才能获取私有属性
        Object o2 = name1.get(obj);
        System.out.println("私有指定属性值： " + o2);
    }
}
